package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.common.PageResult;
import cn.itcast.hotel.dto.HotelPageQueryDTO;
import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.service.HotelService;
import cn.itcast.hotel.vo.HotelVO;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 酒店服务
 *
 * @author liudo
 * @date 2023/08/15
 */
@Service
@RequiredArgsConstructor
public class HotelServiceImpl extends ServiceImpl<HotelMapper, Hotel> implements HotelService {

    public static final String HOTEL = "hotel";
    public static final String BRAND_AGG = "brandAgg";
    public static final String STAR_NAME_AGG = "starNameAgg";
    public static final String CITY_AGG = "cityAgg";

    private final RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult<HotelVO> listPage(HotelPageQueryDTO hotelPageQueryDTO) {
        String key = hotelPageQueryDTO.getKey();
        int from = (hotelPageQueryDTO.getPage() - 1) * hotelPageQueryDTO.getSize();
        SearchRequest searchRequest = new SearchRequest(HOTEL);
        //如果key为空则不拼接条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNoneEmpty(key)){
            boolQueryBuilder.must(QueryBuilders.matchQuery("all",key));
        }else {
            boolQueryBuilder.must(
                    QueryBuilders.matchAllQuery()
            );
        }
        //城市
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getCity())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("city", hotelPageQueryDTO.getCity())
                    );
        }
        //品牌
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getBrand())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("brand", hotelPageQueryDTO.getBrand())
                    );
        }
        //星级
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getStarName())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.termQuery("starName", hotelPageQueryDTO.getStarName())
                    );
        }
        //价格
        if (Objects.nonNull(hotelPageQueryDTO.getMinPrice()) && Objects.nonNull(hotelPageQueryDTO.getMaxPrice())) {
            boolQueryBuilder
                    .filter(
                            QueryBuilders.rangeQuery("price")
                                    .gte(hotelPageQueryDTO.getMinPrice())
                                    .lte(hotelPageQueryDTO.getMaxPrice())
                    );
        }
        searchRequest.source().query(boolQueryBuilder);
        //查询boolQueryBuilder
        searchRequest.source().query(
                QueryBuilders.functionScoreQuery(
                        boolQueryBuilder,
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                        QueryBuilders.termQuery("ad", true),
                                        ScoreFunctionBuilders.weightFactorFunction(10F))
                        }
                ).boostMode(CombineFunction.SUM)
        );
        //排序
        if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getLocation())){
            searchRequest.source().sort(
                    SortBuilders.geoDistanceSort("location",new GeoPoint(hotelPageQueryDTO.getLocation()))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        }
        //分页
        searchRequest.source()
                .from(from)
                .size(hotelPageQueryDTO.getSize());

        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();
            List<HotelVO> hotelVOS = Arrays.stream(hitsHits).map(hit -> {
                String sourceAsString = hit.getSourceAsString();
                HotelVO hotelVO = JSON.parseObject(sourceAsString, HotelVO.class);
                if (StringUtils.isNoneEmpty(hotelPageQueryDTO.getLocation())){
                    Object[] sortValues = hit.getSortValues();
                    if (sortValues != null && sortValues.length > 0){
                        Object sortValue = sortValues[0];
                        hotelVO.setDistance(sortValue);
                    }
                }
                return hotelVO;
            }).collect(Collectors.toList());
            PageResult<HotelVO> pageResult = new PageResult<>();
            pageResult.setTotal(total);
            pageResult.setData(hotelVOS);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public Map<String, List<String>> filter(HotelPageQueryDTO hotelPageQueryDTO) {
        SearchRequest searchRequest = new SearchRequest(HOTEL);
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(hotelPageQueryDTO);
        searchRequest.source()
                .query(boolQueryBuilder)
                .size(0)
                .aggregation(
                        AggregationBuilders
                                .terms(BRAND_AGG)
                                .field("brand")
                                .size(20)
                )
                .aggregation(
                        AggregationBuilders
                                .terms(CITY_AGG)
                                .field("city")
                                .size(20)
                )
                .aggregation(
                        AggregationBuilders
                                .terms(STAR_NAME_AGG)
                                .field("starName")
                                .size(20)
                );

        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            ParsedStringTerms aggregationBrand = aggregations.get(BRAND_AGG);
            ParsedStringTerms aggregationCity = aggregations.get(CITY_AGG);
            ParsedStringTerms aggregationStarName = aggregations.get(STAR_NAME_AGG);
            List<? extends Terms.Bucket> bucketsBrand = aggregationBrand.getBuckets();
            List<String> brandCollect = bucketsBrand.stream().map(bucket -> {
                        String keyAsString = bucket.getKeyAsString();
                        return keyAsString;
                    }
            ).collect(Collectors.toList());
            List<? extends Terms.Bucket> bucketsCity = aggregationCity.getBuckets();
            List<String> cityCollect = bucketsCity.stream().map(bucket -> {
                String keyAsString = bucket.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            List<? extends Terms.Bucket> bucketsStarName = aggregationStarName.getBuckets();
            List<String> startNameCollect = bucketsStarName.stream().map(bucket -> {
                String keyAsString = bucket.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());
            Map<String,List<String>> result = new HashMap<>();
            result.put("brand",brandCollect);
            result.put("city",cityCollect);
            result.put("starName",startNameCollect);
            return result;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @Override
    public List<String> suggestion(String key) {
        SearchRequest searchRequest = new SearchRequest(HOTEL);
        String suggestionSuggest = "suggestionSuggest";
        searchRequest.source()
                .suggest(
                        new SuggestBuilder()
                                .addSuggestion(
                                        suggestionSuggest,
                                        SuggestBuilders.completionSuggestion("suggestion")
                                                .prefix(key)
                                                .skipDuplicates(true)
                                                .size(10)
                                )
                );
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            Suggest suggest = response.getSuggest();

            CompletionSuggestion completionSuggestion = suggest.getSuggestion(suggestionSuggest);
            List<CompletionSuggestion.Entry.Option> options = completionSuggestion.getOptions();
            List<String> collect = options.stream()
                    .map(option -> {
                        String string = option.getText().string();
                        return string;
                    }).collect(Collectors.toList());
            return collect;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static BoolQueryBuilder getBoolQueryBuilder(HotelPageQueryDTO hotelPageQueryDTO) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 需求一的查询
        if (StringUtils.isBlank(hotelPageQueryDTO.getKey())) {
            // 2.1 如果key为空则查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // 2.2 如果key不为空则查询all字段
            boolQuery.must(QueryBuilders.matchQuery("all", hotelPageQueryDTO.getKey()));
        }
        // 需求二：支持通过 城市、星级、品牌、价格区间 进行过滤数据
        if (StringUtils.isNoneBlank(hotelPageQueryDTO.getCity())) {
            // 城市不为空，则增加城市条件
            boolQuery.filter(QueryBuilders.matchQuery("city", hotelPageQueryDTO.getCity()));
        }
        if (StringUtils.isNoneBlank(hotelPageQueryDTO.getStarName())) {
            // 星级不为空，则增加星级条件
            boolQuery.filter(QueryBuilders.matchQuery("starName", hotelPageQueryDTO.getStarName()));
        }
        if (StringUtils.isNoneBlank(hotelPageQueryDTO.getBrand())) {
            // 品牌不为空，则增加品牌条件
            boolQuery.filter(QueryBuilders.matchQuery("brand", hotelPageQueryDTO.getBrand()));
        }
        if (Objects.nonNull(hotelPageQueryDTO.getMinPrice()) &&
                Objects.nonNull(hotelPageQueryDTO.getMaxPrice())) {
            // 价格不为空，则增加价格条件
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .lt(hotelPageQueryDTO.getMaxPrice())
                    .gt(hotelPageQueryDTO.getMinPrice())
            );
        }
        return boolQuery;
    }
}
